package com.android.test.view;

import java.util.ArrayList;

import com.android.test.model.EntryAdapter;
import com.android.test.model.OrgDetailInfo;
import com.android.test.view.DetailGallery.RequestOrgListener;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;



public class DetailGallery extends HorizontalScrollView/* implements GestureDetector.OnGestureListener*/{
	
	private static final int TOUCH_STATE_REST = 0;
	private static final int TOUCH_STATE_SCROLLING = 1;
	private static final int ITEM_DEFUALT_COUNT = 6;
	
	private static final int CHILD_VIEW_WIDTH = 420;
	private static final int CHILD_VIEW_HEIGHT = 600;

	
	private float mLastMotionY;
	private float mLastMotionX;
	private int mTouchSlop;
	private int mTouchState = TOUCH_STATE_REST;
	private Context mContext;
	private LinearLayout mAllLayout;
	private EntryAdapter mAdapter;
	private int mSelectedPosition = 0;
	private int mChildViewEdge = 20;
	private int mScreenWidth = 480;
	private int mScreenHeight = 800;
	private LinearLayout mParentLayout;
	private float mLastScrollX = 0;
	private float mLastScrollY = 0;
	private int mScrollX = 0;
	private boolean isLockView = false;
	private boolean isLeft = true;
	private ArrayList<OrgDetailInfo> mStockList = new ArrayList<OrgDetailInfo>();
	private ArrayList<ChildLayout> mChildViewList = new ArrayList<ChildLayout>();
	
	private RequestOrgListener mRequestOrgListener;
	
	public static interface RequestOrgListener {
		void onResult(int type, boolean isRequest);
	}
	
	private DataSetObserver mObserver = new DataSetObserver() {

		@Override
		public void onChanged() {
			
		}
		
	};
	private GestureDetector mGestureDetector;
	
	private class ChildLayout extends LinearLayout {
		
		private int mId = 0;
		
		public ChildLayout(Context context) {
			super(context);
		}

		public void setId(int position) {
			mId = position;
		}
		
		@Override
		protected void onLayout(boolean changed, int l, int t, int r, int b) {
			super.onLayout(changed, l, t, r, b);
		}

		@Override
		public boolean dispatchTouchEvent(MotionEvent ev) {
			System.out.println(">>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Touch <<<<<<" + mId);
			setSelectedPosition(mId);
			return super.dispatchTouchEvent(ev);
		}		
		
		private void setSelectedPosition(int position) {
			mSelectedPosition = position;
		}
		
	}
	public DetailGallery(Context context) {
		this(context, null);
	}
	
	public DetailGallery(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}
	
	public DetailGallery(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		init();
	}

	private void init() {
		mParentLayout = new LinearLayout(mContext);
		mAllLayout = new LinearLayout(mContext);
		mAllLayout.setOrientation(LinearLayout.HORIZONTAL);
		mAllLayout.setGravity(Gravity.CENTER_HORIZONTAL);
		TextView anchorLeft = new TextView(mContext);
		anchorLeft.setVisibility(View.INVISIBLE);
		TextView anchorRight = new TextView(mContext);
		anchorLeft.setVisibility(View.INVISIBLE);
		mAllLayout.addView(anchorLeft, new LayoutParams(25, mScreenHeight));	
		mAllLayout.addView(mParentLayout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		mAllLayout.addView(anchorRight, new LayoutParams(25, mScreenHeight));
		this.addView(mAllLayout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		mAdapter = new EntryAdapter(mContext);
		mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
	}
	

	
	public void unregisterListener() {
		mRequestOrgListener = null;
	}
	
	public void setAdapter(EntryAdapter adapter) {
		if (!mAdapter.isEmpty()) {
			mAdapter.unregisterDataSetObserver(mObserver);
			mAdapter.clear();
			mAllLayout.removeAllViews();
		}
		mAdapter = adapter;
		mAdapter.registerDataSetObserver(mObserver);
		if (!mAdapter.isEmpty()) {
			setDataLayout();
		}
	}

	public void setScreenXY(int width, int height){
		if (width > 0 && height > 0) {
			this.mScreenWidth = width;
			this.mScreenHeight = height;
			int temX = mScreenWidth - CHILD_VIEW_WIDTH;
			mChildViewEdge = temX / 2;
		}
	}

	private void fetchMoreOrg(){
		if (mRequestOrgListener != null) {
			mRequestOrgListener.onResult(-1, true);
		}
	}
	
	public void addOrgList(ArrayList<OrgDetailInfo> list) {
		if (list.isEmpty()) {
			return;
		}
		mAdapter.add(list);
		setDataLayout();
	}
	
	private void setDataLayout() {
		int startIndex = mParentLayout.getChildCount();
		Log.e("ZZY", "msg"+startIndex);
		int index = mAdapter.getCount() - startIndex < ITEM_DEFUALT_COUNT ? mAdapter.getCount() - startIndex 
				: ITEM_DEFUALT_COUNT;
		if ((mAdapter.getCount() - startIndex) <= ITEM_DEFUALT_COUNT) {
			fetchMoreOrg();
		}
		for (int i = startIndex; i < index + startIndex; i++) {
			View view = mAdapter.getView(i, null, this);
			ChildLayout child = new ChildLayout(mContext);
			child.addView(view);
			child.setId(i);
			child.setPadding(2, 0, 2, 0);
			mChildViewList.add(child);
			mParentLayout.addView(child, new LayoutParams(CHILD_VIEW_WIDTH + 10, CHILD_VIEW_HEIGHT + 70));
		}
		setMaxMove(mParentLayout.getChildCount());
	}
	
	private void setMaxMove(int index) {
//		mXLimit = (index - 1) * mScreenWidth;
	}
	
	public int getSelectedViewDetails(int offset) {
		if (Math.abs(offset) > CHILD_VIEW_WIDTH / 5 && isLeft) {
			mSelectedPosition++;
		}else if (!isLeft && Math.abs(offset) > CHILD_VIEW_WIDTH / 5) {
			mSelectedPosition--;
		}
		if (isLeft && mSelectedPosition >= mParentLayout.getChildCount()) {
			mSelectedPosition = mParentLayout.getChildCount() - 1;
		}else if (!isLeft && mSelectedPosition <= 0) {
			mSelectedPosition = 0;
		}
		System.out.println(">>>>>>>>> mSelectedPosition = " + mSelectedPosition);
		System.out.println(">>>>>>>>> offset = " + offset);
		View view = mChildViewList.get(mSelectedPosition);
		return view.getLeft();
	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		final int action = ev.getAction();
		final float x = ev.getX();
		final float y = ev.getY();
		switch (action){
		case MotionEvent.ACTION_DOWN:
			mLastMotionX = x;
			mLastMotionY = y;
			mLastScrollX = x;
			mLastScrollY = y;
			mTouchState = TOUCH_STATE_REST;
			break;
		case MotionEvent.ACTION_MOVE:
			final int xDiff = (int) Math.abs(x - mLastMotionX);
			final int yDiff = (int) Math.abs(y - mLastMotionY);
			if (xDiff < yDiff) {
				return false;
			}
			boolean xMoved = xDiff > mTouchSlop;
			if (xMoved) {
				mTouchState = TOUCH_STATE_SCROLLING;
			}
			break;
		case MotionEvent.ACTION_UP:
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		return mTouchState != TOUCH_STATE_REST;
	}

    private void scrollIntoSlots(boolean isLeft, int index) {
    	int offsetCount = index;
    	int selectViewLeft = getSelectedViewDetails(offsetCount);
    	int scrollX = getScrollX();
    	int offset = selectViewLeft - scrollX;
        if (isLeft) {
        	if (Math.abs(offsetCount) > CHILD_VIEW_WIDTH / 5) {
        		isLockView = false;
        		smoothScrollBy(offset, 0);
    		}else {
    			smoothScrollTo(selectViewLeft, 0);
			}
		}else {
        	if (Math.abs(offsetCount) > CHILD_VIEW_WIDTH / 5) {
        		isLockView = false;
            	smoothScrollBy(offset, 0);
    		}else {
    			smoothScrollTo(selectViewLeft, 0);
			}
		}
		mScrollX = 0;
    }

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		
		final int action = ev.getAction();
		final float x = ev.getX();
		final float y = ev.getY();
		switch (action){
		case MotionEvent.ACTION_DOWN:
			mLastScrollX = x;
			mLastScrollY = y;
//			mScrollX = 0;
			break;
		case MotionEvent.ACTION_MOVE:
			if (ev.getPointerCount() == 1) {
				float deltaX = mLastScrollX - x;
				float deltaY = mLastScrollY - y;
				
				if (Math.abs(deltaX) < Math.abs(deltaY)) {
//					mScrollX = 0;
//					return false;
				}
				mScrollX += deltaX;
				isLockView = true;
				smoothScrollBy((int) deltaX, 0);
				System.out.println(">>>>>>>>> wight Scroll X = " + getScrollX());
				System.out.println(">>>>>>>>> mScrollX = " + mScrollX);
				mLastScrollX = x;
				mLastScrollY = y;
			} 
			break;
		case MotionEvent.ACTION_UP:		
			isLeft = mScrollX >= 0 ? true : false;
			scrollIntoSlots(isLeft, mScrollX);
			float range = (computeHorizontalScrollOffset() * 100) / computeHorizontalScrollRange();
			if (range >=65) {
				setDataLayout();
			}
			mTouchState = TOUCH_STATE_REST;
			break;
		}
		return false;
	}

	
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int childLeft = 0;

        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                final int childWidth = child.getMeasuredWidth();
                child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
                childLeft += childWidth;
            }
        }
    }

    public void registerListener(RequestOrgListener listener) {
		mRequestOrgListener = listener;
    }


//	@Override
//	public boolean onDown(MotionEvent e) {
//		// TODO Auto-generated method stub
//		return false;
//	}
//
//	@Override
//	public void onShowPress(MotionEvent e) {
//		// TODO Auto-generated method stub
//		
//	}
//
//	@Override
//	public boolean onSingleTapUp(MotionEvent e) {
//		// TODO Auto-generated method stub
//		return false;
//	}
//
//	@Override
//	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
//			float distanceY) {
//		// TODO Auto-generated method stub
//		return false;
//	}
//
//	@Override
//	public void onLongPress(MotionEvent e) {
//		// TODO Auto-generated method stub
//		
//	}
//
//	@Override
//	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
//			float velocityY) {
//		// TODO Auto-generated method stub
//		return false;
//	}
}
